﻿using System.Diagnostics;
using System.Timers;
using System.ComponentModel;

namespace TaskManager
{
    /// <summary>
    /// Class is for retrieving the current system performances of the system like total Processor time
    /// and total Memory Usage.
    /// Every 1000ms the performance-values are updated
    /// </summary>

    class SystemPerformance : INotifyPropertyChanged
    {

        private PerformanceCounter _CPUCounterValue = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        private PerformanceCounter _MemCounterValue = new PerformanceCounter("Process", "Working Set", "_Total");


        private double cpuusage;
        private double memusage;


        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string str)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(str));
            }
        }


        private SystemPerformance()
        {

            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_elapsed);
            timer.Enabled = true;
            timer.Start();

        }

        public static SystemPerformance CreateNewSystemPerformance()
        {
            return new SystemPerformance();
        }

        public double CPUUsage
        {
            get { return this.cpuusage; }
            set
            {

                if (value != this.cpuusage)
                {
                    this.cpuusage = value;
                    NotifyPropertyChanged("CPUUsage");
                }
            }
        }

        public double MemUsage
        {
            get { return this.memusage; }
            set
            {
                if (value != this.memusage)
                {
                    this.memusage = value;
                    NotifyPropertyChanged("MemUsage");

                }
            }
        }

        public void MeasureCPUUsage()
        {
            System.Threading.Thread.Sleep(50); //otherwise on startup of the app there would not be shown any Usage
            this.CPUUsage = this._CPUCounterValue.NextValue();
        }

        public void MeasureMemUsage()
        {
            System.Threading.Thread.Sleep(50); //otherwise on startup of the app there would not be shown any Usage
            this.MemUsage = this._MemCounterValue.NextValue() / 1024 / 1024; //convert in displayable format (MB)
        }


        private void timer_elapsed(object sender, ElapsedEventArgs args)
        {
            MeasureCPUUsage();
            MeasureMemUsage();
        }


    }
}
